package com.example.controller;

import com.example.pojo.Result;
import com.example.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/permission")
@Slf4j
public class PermissionController {
    @Autowired
    private PermissionService permissionService;
    /**
     * 绑定用户默认角色
     *
     * @param userId
     * @return
     */
    @PostMapping("/bindDefaultRole")
    public Result bindDefaultRole(@RequestParam Long userId) {

        try {
            log.info("绑定用户{}的默认角色", userId);
            return permissionService.bindDefaultRole(userId);
        } catch (DataAccessException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "绑定用户默认角色的数据库操作失败", e);
        }
    }

    /**
     * 获取用户角色编码
     *
     * @param userId
     * @return
     */
    @PostMapping("/getUserRoleCode")
    public String getUserRoleCode(@RequestParam("userId") Long userId) {
        try {
            log.info("获取用户{}的角色编码", userId);
            return permissionService.getUserRoleCode(userId);
        } catch (DataAccessException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "获取用户角色编码的数据库操作失败", e);
        }
    }
    //超管调用：升级用户为管理员
    @PostMapping("/upgradeUser")
    public void upgradeUser(@RequestParam Long userId) {
        try {
            log.info("升级用户{}为管理员", userId);
            permissionService.upgradeUser(userId);
        } catch (DataAccessException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "升级用户为管理员的数据库操作失败", e);
        }
    }

    /**
     * 超管调用：降级用户为普通角色
     * @param userId
     * @return
     */
    @PostMapping("/downgradeUser")
    public void downgradeUser(@RequestParam Long userId) {
        try {
            log.info("降级用户{}为普通用户", userId);
            permissionService.downgradeUser(userId);
        } catch (DataAccessException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "降级用户为普通用户的数据库操作失败", e);
        }
    }
}
